::功能：解析可执行文件的主要依赖并复制dll到可执行文件目录下。支持附加搜索路径
::原理：用vs的dumpbin解析dll依赖，where找到dll路径，copy过来。
::使用：get_dll.bat exe文件路径

@echo off

SETLOCAL ENABLEDELAYEDEXPANSION

echo;
echo Step1. initialize environment

::设置相关变量
set search_path="C:\Qt\5.15.2\msvc2019"
::set search_path2="%SystemRoot%\SysWow64"
::set /p vs_root_path=visual studio 安装根目录(eg.E:\VS2015):
set vs_root_path="C:\Program Files (x86)\Microsoft Visual Studio 14.0"

set dumpbin_path=%vs_root_path%\VC\bin\dumpbin.exe
set exe_path=%1
set dll_path=%~dp1
set depends_file=%dll_path%\_depends.txt
set paths_file=%dll_path%\_paths.txt
set log_file=%dll_path%\_error.log

echo execute path: %exe_path%
echo dumpbin path: %dumpbin_path%
echo search path: %search_path%
echo additional search path: %search_path2%

if not exist %dll_path% (
md %dll_path% >nul
)

echo;
echo Step2. parse depends

::第一层依赖
%dumpbin_path% /dependents %exe_path% | findstr "\.dll$" >%depends_file%

if exist %paths_file% (
del %paths_file%
)

for /f "usebackq" %%i in (%depends_file%) do (
where /R %search_path% %%i 1>> %paths_file% 2>nul
if errorlevel 1 (
where /R %search_path2% %%i 1>> %paths_file% 2>nul
if errorlevel 1 (
echo cannot find %%i
echo %%i>>%log_file%
)
)
)

::第二层依赖
for /f "usebackq" %%i in (%paths_file%) do (
%dumpbin_path% /dependents %%i | findstr "\.dll$" | findstr /V "Dump" >>%depends_file%
)

echo;
echo Step3. find the path of depends

del %paths_file%

for /f "usebackq" %%i in (%depends_file%) do (
echo %%i
where /R %search_path% %%i 1>> %paths_file% 2>nul
if errorlevel 1 (
where /R %search_path2% %%i 1>> %paths_file% 2>nul
if errorlevel 1 (
echo cannot find %%i
echo %%i>>%log_file%
)
)
)

echo;
echo Step4. copy depends to %dll_path%\

for /f "usebackq" %%i in (%paths_file%) do (
echo %%i
if not %%~i=="gdiplus.dll" (
copy %%i %dll_path%\
)
)

echo;
echo job is done

:end
echo;
echo Note: There may be still some depends lacking, please run add_dll.bat to obtain them one by one.
pause
